package com.example.java_gobang.api;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.java_gobang.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@Slf4j
@RequestMapping("/captcha")
@RestController
public class HuToolCaptchaAPI {
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void getCode(HttpSession session, HttpServletResponse response) {
        //定义图形验证码的⻓和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        response.setContentType("image/jpeg");
        //禁⽌使⽤缓存
        response.setHeader("Pragma", "No-cache");
        try {
            // 输出到⻚⾯
            lineCaptcha.write(response.getOutputStream());
            //存储在Session中
            log.info("生成验证码： " + lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private final static long VALID_MILLIS_TIME = 60 * 1000;

    @RequestMapping("/check")
    public boolean checkHomeCaptcha(String captcha, HttpSession session) {
        log.info("用户输入验证码： " + captcha);
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        String savedCaptcha = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date sessionDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if (captcha.equalsIgnoreCase(savedCaptcha)) {
            if (sessionDate == null || System.currentTimeMillis() - sessionDate.getTime() <
                    VALID_MILLIS_TIME) {
                return true;
            }
            return false;
        }
        return false;
    }
}
